#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    int ret = 0;
    int dx[4] = { 1, -1, 0, 0 };
    int dy[4] = { 0, 0, 1, -1 };
    int uniquePathsIII(vector<vector<int>>& grid) {
        vector<vector<bool>> map(grid.size(), vector<bool>(grid[0].size(), false));
        int zero = 0, x, y;
        for (int i = 0; i < grid.size(); i++)
            for (int j = 0; j < grid[0].size(); j++)
                if (grid[i][j] == 1) x = i, y = j;
                else if (grid[i][j] == 0) zero++;
        dfs(grid, map, zero + 1, x, y, 0);
        return ret;
    }
    void dfs(vector<vector<int>>& grid, vector<vector<bool>>& map, int zero, int x, int y, int count)
    {
        if (grid[x][y] == 2)
        {
            if (zero == count) ret++;
            return;
        }

        for (int k = 0; k < 4; k++)
        {
            int a = x + dx[k], b = y + dy[k];
            if (a >= 0 && a < grid.size() && b >= 0 && b < grid[a].size() && map[a][b] == false && grid[a][b] != -1)
            {
                map[x][y] = true;
                dfs(grid, map, zero, a, b, count + 1);
                map[x][y] = false;
            }
        }
    }
};